package com.gusto.engine.repository.dao.impl;

import org.apache.log4j.Logger;

import com.gusto.engine.beans.exceptions.ResCreationException;
import com.gusto.engine.beans.model.Res;
import com.gusto.engine.beans.model.impl.SemanticModelRes;
import com.gusto.engine.repository.dao.RepositoryDAO;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.ModelMaker;

/**
 * <p>Implements {@link RepositoryDAO}, 
 * and defines a DAO for a the Jena Semantic Repository.</p>
 * 
 * @author amokrane.belloui@gmail.com
 */
public class SemanticRepositoryDAO implements RepositoryDAO {
	
	// TODO Unit tests
	
	private Logger log = Logger.getLogger(SemanticRepositoryDAO.class);
	
	private ModelMaker modelMaker;
	private Model model;
	private String modelName;
	
	/**
	 * Sets the Jena ModelMaker
	 * @param modelMaker
	 */
	public void setModelMaker(ModelMaker modelMaker) {
		this.modelMaker = modelMaker;
		createModel();
	}
	
	/**
	 * Sets the name for the model that will be created and then used
	 * @param modelName
	 */
	public void setModelName(String modelName) {
		this.modelName = modelName;
		createModel();
	}
	
	/**
	 * Creates the Jena Model
	 */
	private void createModel() {
		try {
			Model dbModel = modelMaker.openModel(modelName, true);
			OntModel m = ModelFactory.createOntologyModel(OntModelSpec.OWL_DL_MEM_RDFS_INF);
			m.add(dbModel);
			model = m;
			log.debug("Model " + modelName + " created");
		}
		catch (Exception ex) {
			model = null;
		}
	}
	
	/**
	 * {@inheritDoc}
	 */
	public Res getResource(String resourceId) throws ResCreationException {
		return SemanticModelRes.createResource(model.getResource(resourceId));
	}
	
}
